import { EditOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-form';
import React from 'react';

type EditFormProps = {
  name: string;
  model:
    | {
        id: any;
        [key: string]: any;
      }
    | undefined;
  visible: boolean;
  width?: number | string;
  onAdd: (model: any) => Promise<boolean>;
  onUpdate: (fields: any, currentRow?: any) => Promise<boolean>;
  afterEdit: () => void;
  onCancel: (visible: boolean) => void;
};

const EditForm: React.FC<EditFormProps> = (props) => {
  const icon = props.model?.id ? <EditOutlined /> : <PlusCircleOutlined />;
  const title = (props.model?.id ? '编辑' : '新增') + props.name;
  return (
    <ModalForm
      // title={(props.model?.id ? '编辑' : '新增') + props.name}
      title={
        <>
          {icon}
          &nbsp;&nbsp;{title}
        </>
      }
      width={props.width || 640}
      grid={true}
      rowProps={{
        gutter: 20,
      }}
      visible={props.visible}
      onVisibleChange={props.onCancel}
      initialValues={props.model || {}}
      modalProps={{
        destroyOnClose: true,
      }}
      onFinish={async (value) => {
        if (props.model?.id) {
          if (await props.onUpdate(value, props.model)) {
            props.afterEdit();
            return true;
          }
        } else {
          if (await props.onAdd(value)) {
            props.afterEdit();
            return true;
          }
        }

        return false;
      }}
    >
      {props.children}
    </ModalForm>
  );
};

export default EditForm;
